﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dominio;
using Util;
using System.Data.Objects;
using Excepciones;

namespace Servicios
{
    public class LogServiceDataBaseImpl : GenericService<Log>, ILogService
    {
        private TimeManager timeManager = TimeManager.ObtenerInstancia();

        private static LogServiceDataBaseImpl instancia = new LogServiceDataBaseImpl();

        private LogServiceDataBaseImpl() : base() { }

        public static LogServiceDataBaseImpl ObtenerInstancia()
        {
            return instancia;
        }

        protected override ObjectSet<Log> GetObjectSet(DominioContainer ctx)
        {
            return ctx.Logs;
        }

        public override void Registrar(Log t)
        {
            using (Ctx)
            {
                DateTime fecha = timeManager.ObtenerHoraActual();
                t.Fecha = fecha;
                base.Registrar(t);
            }
        }

        public void Modificar(Log log)
        {
            using (DominioContainer ctx = new DominioContainer())
            {
                Log l = null;
                try
                {
                    l = ctx.Logs.First(lo => lo.Id == log.Id);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException("Log no existente en la base de datos.");
                }
                if (l == null)
                {
                    throw new DataBaseException("No existe un log con id " + log.Id + " en la base de datos.");
                }
                l.Accion = log.Accion;
                l.Fecha = log.Fecha;
                l.Keyword = log.Keyword;
                l.UsuarioId = log.UsuarioId;

                ctx.SaveChanges();
            }
        }

        public Log ObtenerPorId(int id)
        {
            using (DominioContainer ctx = new DominioContainer())
            {
                try
                {
                    Log log = ctx.Logs.First(l => l.Id == id);
                    return log;
                }
                catch (Exception ex)
                {
                    throw new DataBaseException();
                }
            }
        }
    }
}
